package com.poizon.infrastructure.idem.starter.redis;

import com.poizon.infrastructure.idem.core.repo.IIdemDbStoreRepo;
import com.poizon.infrastructure.idem.core.util.IRepeatedSubmitUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import redis.clients.jedis.JedisPoolConfig;

@Slf4j
@Import(RepeatedSubmitUtil.class)
public class RedisDbStoreAutoConfig {
    @Value("${idem.redis.host:127.0.0.1}")
    private String host;
    @Value("${idem.redis.port:6379}")
    private Integer port;
    @Value("${idem.redis.database:0}")
    private Integer database;

    @Bean(name = "idemStringRedisTemplate")
    public StringRedisTemplate idemStringRedisTemplate() {
        log.info("[通用幂等框架] 初始化idemStringRedisTemplate");
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(1000);
        poolConfig.setMaxIdle(1000);
        poolConfig.setMinIdle(1000);
        JedisConnectionFactory factory = new JedisConnectionFactory(poolConfig);
        factory.setHostName(host);
        factory.setPort(port);
        factory.setDatabase(database);
        factory.afterPropertiesSet();
        StringRedisTemplate redisTemplate = new StringRedisTemplate();
        redisTemplate.setConnectionFactory(factory);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Bean(value = "redisIdemDbStoreRepo")
    public IIdemDbStoreRepo redisIdemDbStoreRepo(@Qualifier(value = "idemStringRedisTemplate") StringRedisTemplate stringRedisTemplate) {
        log.info("[通用幂等框架] 成功初始化幂等存储实现redis");
        return new RedisIdemDbStoreRepo(stringRedisTemplate);
    }

    @Bean
    public IRepeatedSubmitUtil repeatedSubmitUtil(@Qualifier(value = "idemStringRedisTemplate") StringRedisTemplate redisTemplate) {
        log.info("[通用幂等框架] 成功初始化防重框架");
        return new RepeatedSubmitUtil(redisTemplate);
    }
}
